import React from 'react'
import Header from '@/components/Header'
import '@/pages/index.less'
import Link from 'next/link'
import conf from '@/config'
import { avatar } from '@/helper/facebook'
//
import { FacebookProvider, Login } from 'react-facebook'
import cookie from 'react-cookies'
//
import { inject, observer } from 'mobx-react'
@inject('mangaStore', 'userStore')
@observer
class Home extends React.Component {
  static async getInitialProps({ query, mobxStore, req, res }) {
    // 同构专用
    if (req) cookie.plugToRequest(req, res)
    await mobxStore.mangaStore.getMangeList()
    mobxStore.userStore.loadUser()
    return { query }
  }
  Logout = () => {
    this.props.userStore.logout()
  }
  UserBox(user) {
    return (
      <div id={user.uid}>
        <img src={avatar(user.fbid)} />
        <p>{user.name}</p>
        <button onClick={this.Logout}>Logout</button>
      </div>
    )
  }
  handleResponse = (user) => {
    this.props.userStore.authByfacebook(user)
  }
  handleError = (e) => {
    console.error(e)
  }
  FacebookLogin() {
    return (
      <FacebookProvider appId={conf.facebook.appId}>
        {/* <LoginButton
          className="fb-login"
          scope="email"
          onCompleted={this.handleResponse}
          onError={this.handleError}
        >
          <span>Login via Facebook</span>
        </LoginButton> */}
        <Login
          scope="email"
          onCompleted={this.handleResponse}
          onError={this.handleError}
        >
          {({ loading, handleClick, error, data }) => (
            <span className="fb-login" onClick={handleClick}>
              Login via Facebook
              {loading && (
                <span>Loading...</span>
              )}
            </span>
          )}
        </Login>
      </FacebookProvider>
    )
  }
  Genres(list) {
    return list.map((item) => {
      return (<span key={item}>{item}</span>)
    })
  }
  List(list) {
    return list.map(data => {
      return (
        <Link key={data._id} href={`/manga?id=${data._id}`}>
          <div className="manga-detail">
            <img src={conf.cdn(data.image)} />
            <h1>{data.title}</h1>
            <p>Status{data.status}</p>
            <p className="tags">{this.Genres(data.genres)}</p>
          </div>
        </Link>
      )
    })
  }
  render() {
    const { list } = this.props.mangaStore
    const { user } = this.props.userStore
    return (
      <div className="Home">
        <Header title="Home" />
        {(user) ? this.UserBox(user) : this.FacebookLogin()}
        {this.List(list)}
      </div>
    )
  }
}

export default Home
